package com.example.oasystem.controller.process;

import com.example.oasystem.config.ConstantProperties;

import com.example.oasystem.dao.attachment.AoaAttachmentListDaoOfJian;
import com.example.oasystem.dao.dept.AoaDeptDao;
import com.example.oasystem.dao.position.AoaPositionDao;
import com.example.oasystem.dao.subject.AoaSubjectDaoOfJian;
import com.example.oasystem.dao.type.AoaTypeListDao;
import com.example.oasystem.entity.attachment.AoaAttachmentListOfJian;
import com.example.oasystem.entity.burse.AoaBursementOfJian;
import com.example.oasystem.entity.dept.AoaDept;
import com.example.oasystem.entity.holiday.AoaHolidayOfJian;
import com.example.oasystem.entity.page.Page;
import com.example.oasystem.entity.position.AoaPosition;
import com.example.oasystem.entity.regular.AoaRegularOfJian;
import com.example.oasystem.entity.resign.AoaResignOfJian;
import com.example.oasystem.entity.subject.AoaSubjectOfJian;
import com.example.oasystem.entity.type.AoaTypeList;
import com.example.oasystem.entity.user.AoaUser;
import com.example.oasystem.service.AoaBursementServiceOfJian;
import com.example.oasystem.service.AoaUserService;
import com.example.oasystem.utils.AliyunOSSUtil;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author 10440
 */
@Controller
public class CreateProcessControllerOfJian {
    @Autowired
    private ConstantProperties constantProperties;
    @Autowired
    private AoaTypeListDao aoaTypeListDao;
    @Autowired
    private AoaDeptDao aoaDeptDao;
    @Autowired
    private AoaPositionDao aoaPositionDao;
    @Autowired
    private AoaSubjectDaoOfJian aoaSubjectDaoOfJian;
    @Autowired
    private AoaUserService aoaUserService;
    @Autowired
    private AliyunOSSUtil aliyunOSSUtil;
    @Autowired
    private AoaBursementServiceOfJian aoaBursementServiceOfJian;
    @Autowired
    private AoaAttachmentListDaoOfJian aoaAttachmentListDaoOfJian;

    @RequestMapping("/xinxeng")
    public String xinxeng(){
        return "process/procedure";
    }

    @RequestMapping("/burse")
    public String burse(Model model, HttpSession session,
                        @RequestParam(value = "pageNum", required = false,defaultValue = "1") int pageNum,
                        @RequestParam(value = "pageSize", defaultValue = "4") int pageSize,
                        @RequestParam(value = "baseKey", defaultValue = "") String baseKey){

        List<AoaTypeList> harryList = aoaTypeListDao.selectTypeListByRealModel("aoa_process_list");
        AoaUser user = (AoaUser) session.getAttribute("user");
        List<AoaTypeList> aoaBursement = aoaTypeListDao.selectTypeListByRealModel("aoa_bursement");

        PageInfo<AoaUser> aoaUserList = aoaUserService.selectAllDeptAndPosition2(pageNum, pageSize, baseKey,user.getFatherId());

        List<AoaDept> aoaDeptList = aoaDeptDao.selectAll();
        List<AoaPosition> positions = aoaPositionDao.selectAllPositions();
        List<AoaSubjectOfJian> subjects = aoaSubjectDaoOfJian.selectAllSubjects();
        List<AoaSubjectOfJian> parentSubjects = aoaSubjectDaoOfJian.selectParentSubjects();

        Page page=new Page(aoaUserList.getSize(), Math.toIntExact(aoaUserList.getTotal()),aoaUserList.getPages(),aoaUserList.getPageNum(),aoaUserList.isIsFirstPage(),aoaUserList.isIsLastPage());

        model.addAttribute("emplist",aoaUserList.getList());
        model.addAttribute("deptlist",aoaDeptList);
        model.addAttribute("poslist",positions);
        model.addAttribute("second",parentSubjects);
        model.addAttribute("sublist",subjects);

        model.addAttribute("harrylist",harryList);
        model.addAttribute("username",user.getUserName());
        model.addAttribute("uplist",aoaBursement);

        model.addAttribute("baseKey",baseKey);
        model.addAttribute("page",page);
        model.addAttribute("url","bursePaging");

        return "process/bursement";
    }

    @RequestMapping("/bursePaging")
    public String bursePaging(Model model, HttpSession session,
                              @RequestParam(value = "pageNum", required = false,defaultValue = "1") int pageNum,
                              @RequestParam(value = "pageSize", defaultValue = "4") int pageSize,
                              @RequestParam(value = "baseKey", defaultValue = "") String baseKey){
        AoaUser user=(AoaUser) session.getAttribute("user");
        PageInfo<AoaUser> aoaUserList = aoaUserService.selectAllDeptAndPosition2(pageNum, pageSize, baseKey,user.getFatherId());

        List<AoaDept> aoaDeptList = aoaDeptDao.selectAll();
        List<AoaPosition> positions = aoaPositionDao.selectAllPositions();
        Page page=new Page(aoaUserList.getSize(), Math.toIntExact(aoaUserList.getTotal()),aoaUserList.getPages(),aoaUserList.getPageNum(),aoaUserList.isIsFirstPage(),aoaUserList.isIsLastPage());

        model.addAttribute("emplist",aoaUserList.getList());
        model.addAttribute("deptlist",aoaDeptList);
        model.addAttribute("poslist",positions);

        model.addAttribute("baseKey",baseKey);
        model.addAttribute("page",page);
        model.addAttribute("url","bursePaging");
        return "common/reciversOfJian";
    }

    @RequestMapping("/apply")
    public String apply(MultipartFile filePath, HttpSession session,
                        AoaBursementOfJian aoaBursementOfJian){

        System.out.println("aoaBursementOfJian"+":"+aoaBursementOfJian);

        AoaUser user = (AoaUser)session.getAttribute("user");
        Long userId = user.getUserId();
        System.out.println("aoaBursementOfJian = " + aoaBursementOfJian);
        String uploadUrl = null;
        uploadUrl = uploadFile(filePath, uploadUrl);
        AoaAttachmentListOfJian aoaAttachmentListOfJian = new AoaAttachmentListOfJian();
        if (uploadUrl !=null) {
            aoaAttachmentListOfJian.setAttachmentPath(uploadUrl);
            String s = uploadUrl.split("\\?")[0];
            int beginIndex = s.lastIndexOf("/");
            String attachmentName = s.substring(beginIndex+1);
            String attachmentShuffix = attachmentName.split("\\.")[1];
            SimpleDateFormat  sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            aoaAttachmentListOfJian.setModel("attachment_bursement");
            aoaAttachmentListOfJian.setUserId(userId+"");
            aoaAttachmentListOfJian.setUploadTime(sdf.format(new Date()));
            aoaAttachmentListOfJian.setAttachmentShuffix(attachmentShuffix);
            aoaAttachmentListOfJian.setAttachmentName(attachmentName);
            aoaAttachmentListOfJian.setAttachmentType("image/"+attachmentShuffix);
            aoaAttachmentListOfJian.setAttachmentSize(filePath.getSize()+"");
            aoaAttachmentListDaoOfJian.insert(aoaAttachmentListOfJian);
            aoaBursementServiceOfJian.insert(aoaBursementOfJian,aoaAttachmentListOfJian.getAttachmentId(),userId);
        }else {
            aoaBursementServiceOfJian.insert(aoaBursementOfJian,0L,userId);
        }



        return "process/procedure";
    }

    public String uploadFile(MultipartFile filePath, String uploadUrl) {
        try {
            if(null != filePath){
                String filename = filePath.getOriginalFilename();
                if(!"".equals(filename.trim())){
                    File newFile = new File(filename);
                    FileOutputStream os = new FileOutputStream(newFile);
                    os.write(filePath.getBytes());
                    os.close();
                    filePath.transferTo(newFile);
                    //上传到OSS
                    uploadUrl = constantProperties.getHead() + aliyunOSSUtil.upload(newFile) + constantProperties.getEnd();
                }
            }
        }catch (Exception ex) {
            ex.printStackTrace();
        }
        return uploadUrl;
    }

    @RequestMapping("/evection")
    public String evection(Model model, HttpSession session,
                           @RequestParam(value = "pageNum", required = false,defaultValue = "1") int pageNum,
                           @RequestParam(value = "pageSize", defaultValue = "4") int pageSize,
                           @RequestParam(value = "baseKey", defaultValue = "") String baseKey){
        List<AoaTypeList> harryList = aoaTypeListDao.selectTypeListByRealModel("aoa_process_list");
        AoaUser user = (AoaUser) session.getAttribute("user");
        List<AoaTypeList> outtype = aoaTypeListDao.selectTypeListByRealModel("aoa_evection");


        addressBook(model,pageNum,pageSize,baseKey,session);

        model.addAttribute("harrylist",harryList);
        model.addAttribute("username",user.getUserName());
        model.addAttribute("outtypes",outtype);
        return "process/evection";
    }

    @RequestMapping("/evec")
    public String evec(MultipartFile filePath, HttpSession session,
                       AoaBursementOfJian aoaBursementOfJian,
                       @RequestParam Long typeId){
        AoaUser user = (AoaUser)session.getAttribute("user");
        Long userId = user.getUserId();
        //System.out.println("aoaBursementOfJian = " + aoaBursementOfJian);
        String uploadUrl = null;
        uploadUrl = uploadFile(filePath, uploadUrl);
        AoaAttachmentListOfJian aoaAttachmentListOfJian = new AoaAttachmentListOfJian();
        if(uploadUrl !=null){
            aoaAttachmentListOfJian.setAttachmentPath(uploadUrl);
            String s = uploadUrl.split("\\?")[0];
            int beginIndex = s.lastIndexOf("/");
            String attachmentName = s.substring(beginIndex+1);
            String attachmentShuffix = attachmentName.split("\\.")[1];
            SimpleDateFormat  sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            aoaAttachmentListOfJian.setModel("attachment_evection");
            aoaAttachmentListOfJian.setUserId(userId+"");
            aoaAttachmentListOfJian.setUploadTime(sdf.format(new Date()));
            aoaAttachmentListOfJian.setAttachmentShuffix(attachmentShuffix);
            aoaAttachmentListOfJian.setAttachmentName(attachmentName);
            aoaAttachmentListOfJian.setAttachmentType("image/"+attachmentShuffix);
            aoaAttachmentListOfJian.setAttachmentSize(filePath.getSize()+"");
            aoaAttachmentListDaoOfJian.insert(aoaAttachmentListOfJian);
            aoaBursementServiceOfJian.insertEvec(aoaBursementOfJian,aoaAttachmentListOfJian.getAttachmentId(),userId,typeId);
        } else {
            aoaBursementServiceOfJian.insertEvec(aoaBursementOfJian,0L,userId,typeId);
        }



        return "process/procedure";
    }

    @RequestMapping("/overtime")
    public String overtime(Model model, HttpSession session,
                           @RequestParam(value = "pageNum", required = false,defaultValue = "1") int pageNum,
                           @RequestParam(value = "pageSize", defaultValue = "4") int pageSize,
                           @RequestParam(value = "baseKey", defaultValue = "") String baseKey){
        List<AoaTypeList> harryList = aoaTypeListDao.selectTypeListByRealModel("aoa_process_list");
        AoaUser user = (AoaUser) session.getAttribute("user");
        List<AoaTypeList> overtype = aoaTypeListDao.selectTypeListByRealModel("aoa_overtime");

        addressBook(model,pageNum,pageSize,baseKey,session);

        model.addAttribute("harrylist",harryList);
        model.addAttribute("username",user.getUserName());
        model.addAttribute("overtype",overtype);
        return "process/overtime";
    }
    @RequestMapping("/over")
    public String over(HttpSession session,
                       AoaBursementOfJian aoaBursementOfJian,
                       @RequestParam Long typeId){
        AoaUser user = (AoaUser)session.getAttribute("user");
        Long userId = user.getUserId();

        aoaBursementServiceOfJian.insertOver(aoaBursementOfJian,userId,typeId);
        return "process/procedure";
    }


    @RequestMapping("/regular")
    public String regular(Model model, HttpSession session,
                          @RequestParam(value = "pageNum", required = false,defaultValue = "1") int pageNum,
                          @RequestParam(value = "pageSize", defaultValue = "4") int pageSize,
                          @RequestParam(value = "baseKey", defaultValue = "") String baseKey){
        List<AoaTypeList> harryList = aoaTypeListDao.selectTypeListByRealModel("aoa_process_list");
        AoaUser user = (AoaUser) session.getAttribute("user");

        addressBook(model,pageNum,pageSize,baseKey,session);

        model.addAttribute("harrylist",harryList);
        model.addAttribute("username",user.getUserName());
        return "process/regular";
    }

    @RequestMapping("/regu")
    public String regu(HttpSession session,
                       AoaBursementOfJian aoaBursementOfJian,
                       AoaRegularOfJian aoaRegularOfJian){
        AoaUser user = (AoaUser)session.getAttribute("user");
        Long userId = user.getUserId();

        aoaBursementServiceOfJian.insertRegu(aoaBursementOfJian,aoaRegularOfJian,userId);
        return "process/procedure";
    }

    @RequestMapping("/holiday")
    public String holiday(Model model, HttpSession session,
                          @RequestParam(value = "pageNum", required = false,defaultValue = "1") int pageNum,
                          @RequestParam(value = "pageSize", defaultValue = "4") int pageSize,
                          @RequestParam(value = "baseKey", defaultValue = "") String baseKey){

        List<AoaTypeList> harryList = aoaTypeListDao.selectTypeListByRealModel("aoa_process_list");
        AoaUser user = (AoaUser) session.getAttribute("user");
        List<AoaTypeList> overtype = aoaTypeListDao.selectTypeListByRealModel("aoa_holiday");

        addressBook(model,pageNum,pageSize,baseKey,session);

        model.addAttribute("overtype",overtype);
        model.addAttribute("harrylist",harryList);
        model.addAttribute("username",user.getUserName());
        return "process/holiday";
    }

    @RequestMapping("/holi")
    public String holi(HttpSession session,MultipartFile filePath,
                       AoaBursementOfJian aoaBursementOfJian,
                       AoaHolidayOfJian aoaHolidayOfJian){
        AoaUser user = (AoaUser)session.getAttribute("user");
        Long userId = user.getUserId();

        String uploadUrl = null;
        uploadUrl = uploadFile(filePath, uploadUrl);
        AoaAttachmentListOfJian aoaAttachmentListOfJian = new AoaAttachmentListOfJian();
        if(uploadUrl !=null){
            aoaAttachmentListOfJian.setAttachmentPath(uploadUrl);
            String s = uploadUrl.split("\\?")[0];
            int beginIndex = s.lastIndexOf("/");
            String attachmentName = s.substring(beginIndex+1);
            String attachmentShuffix = attachmentName.split("\\.")[1];
            SimpleDateFormat  sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            aoaAttachmentListOfJian.setModel("attachment_evection");
            aoaAttachmentListOfJian.setUserId(userId+"");
            aoaAttachmentListOfJian.setUploadTime(sdf.format(new Date()));
            aoaAttachmentListOfJian.setAttachmentShuffix(attachmentShuffix);
            aoaAttachmentListOfJian.setAttachmentName(attachmentName);
            aoaAttachmentListOfJian.setAttachmentType("image/"+attachmentShuffix);
            aoaAttachmentListOfJian.setAttachmentSize(filePath.getSize()+"");
            aoaAttachmentListDaoOfJian.insert(aoaAttachmentListOfJian);
            aoaBursementServiceOfJian.insertHoli(aoaBursementOfJian,aoaHolidayOfJian,aoaAttachmentListOfJian.getAttachmentId(),userId);
        } else {
            aoaBursementServiceOfJian.insertHoli(aoaBursementOfJian,aoaHolidayOfJian,0L,userId);
        }


        return "process/procedure";
    }

    @RequestMapping("/resign")
    public String resign(Model model, HttpSession session,
                         @RequestParam(value = "pageNum", required = false,defaultValue = "1") int pageNum,
                         @RequestParam(value = "pageSize", defaultValue = "4") int pageSize,
                         @RequestParam(value = "baseKey", defaultValue = "") String baseKey){
        List<AoaTypeList> harryList = aoaTypeListDao.selectTypeListByRealModel("aoa_process_list");
        AoaUser user = (AoaUser) session.getAttribute("user");

        addressBook(model,pageNum,pageSize,baseKey,session);

        model.addAttribute("harrylist",harryList);
        model.addAttribute("username",user.getUserName());
        return "process/resign";
    }

    @RequestMapping("/res")
    public String res(HttpSession session, AoaBursementOfJian aoaBursementOfJian,
                      AoaResignOfJian aoaResignOfJian,
                      @RequestParam String handusername,
                      String finish){
        AoaUser user = (AoaUser)session.getAttribute("user");
        Long userId = user.getUserId();
        if(finish != null){
            aoaResignOfJian.setIsFinish(false);
        }else {
            aoaResignOfJian.setIsFinish(true);
        }

        aoaBursementServiceOfJian.insertRes(aoaBursementOfJian,aoaResignOfJian,handusername,userId);
        return "process/procedure";
    }

    public void addressBook(Model model, int pageNum, int pageSize, String baseKey,HttpSession session){
        AoaUser user=(AoaUser)session .getAttribute("user");
        PageInfo<AoaUser> aoaUserList = aoaUserService.selectAllDeptAndPosition2(pageNum, pageSize, baseKey,user.getFatherId());
        List<AoaDept> aoaDeptList = aoaDeptDao.selectAll();
        List<AoaPosition> positions = aoaPositionDao.selectAllPositions();
        Page page=new Page(aoaUserList.getSize(), Math.toIntExact(aoaUserList.getTotal()),aoaUserList.getPages(),aoaUserList.getPageNum(),aoaUserList.isIsFirstPage(),aoaUserList.isIsLastPage());

        model.addAttribute("emplist",aoaUserList.getList());
        model.addAttribute("deptlist",aoaDeptList);
        model.addAttribute("poslist",positions);

        model.addAttribute("baseKey",baseKey);
        model.addAttribute("page",page);
        model.addAttribute("url","bursePaging");
    }
}
